package com.glorysoft.wangnianxinpda.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.glorysoft.wangnianxinpda.R;
import com.glorysoft.wangnianxinpda.adapter.MaterialAdapter;
import com.glorysoft.wangnianxinpda.base.App;
import com.glorysoft.wangnianxinpda.base.BaseActivity;
import com.glorysoft.wangnianxinpda.base.Constant;
import com.glorysoft.wangnianxinpda.databinding.ActivityBatchWorkBeginBinding;
import com.glorysoft.wangnianxinpda.entity.PDALotInfoReturnEntity;
import com.glorysoft.wangnianxinpda.entity.MaterialInfoEntity;
import com.glorysoft.wangnianxinpda.entity.net.ResponseEntity;
import com.glorysoft.wangnianxinpda.utils.GsonUtils;
import com.glorysoft.wangnianxinpda.utils.MyUtils;
import com.glorysoft.wangnianxinpda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_JsonUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class BatchWorkBeginActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext;
    private Activity activity;

    private ActivityBatchWorkBeginBinding binding = null;

    private String sEqpId = "";//设备号
    private String sLotId = "";//批次号
    private List<MaterialInfoEntity> mMaterialInfoList = null;//应使用的物料
    private MaterialAdapter materialAdapter;//应上物料适配器

    private PDALotInfoReturnEntity mPDALotInfoReturnEntity;//设备信息


    @Override
    protected void onStart() {
        super.onStart();
        requestData();//获取设备信息
    }

    @Override
    protected int getLayoutResId() {
        return 0;
    }

    @Override
    protected void initView() {
        mContext = this;
        activity = this;
        binding = DataBindingUtil.setContentView(this, R.layout.activity_batch_work_begin);

        binding.btnQuery.setOnClickListener(this);
        binding.llMaterialLayout.setOnClickListener(this);

        binding.etLot.requestFocus();

    }

    @Override
    protected void initData() {
        Bundle extras = getIntent().getExtras();
        sEqpId = extras.getString("EQPID");

        mMaterialInfoList = new ArrayList<>();
        mPDALotInfoReturnEntity = new PDALotInfoReturnEntity();

        MyUtils.setEditTextListener(binding.etLot, mContext, s -> {
            sLotId = s;
            binding.etLot.requestFocus();
            requestData();//获取设备信息

        });


        //初始化物料适配器
        materialAdapter = new MaterialAdapter(R.layout.item_materiel, mMaterialInfoList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        binding.rvMaterialList.setLayoutManager(linearLayoutManager);
        binding.rvMaterialList.setAdapter(materialAdapter);

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle(getString(R.string.batchStartOperation));
        freeUI_titleView.setRightListener(getString(R.string.startWork), v -> startProcess());
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), binding.llMain);
    }

    //region 接口调用

    //获取设备信息
    private void requestData() {
        FreeUI_EntityCallBack<ResponseEntity<PDALotInfoReturnEntity>> callBack = new FreeUI_DialogEntityCallBack<ResponseEntity<PDALotInfoReturnEntity>>(new TypeToken<ResponseEntity<PDALotInfoReturnEntity>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseEntity<PDALotInfoReturnEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(true, getSupportFragmentManager())) {
                    showToast(getString(R.string.success), true);

                    mPDALotInfoReturnEntity = response.body().getData();
                    //region 测试
//                    String sJson = "{\n" +
//                            "          \"HEADER\":           {\n" +
//                            "                    \"TRANSACTIONID\": \"EDA123446-6CF1-5B29-860B-631D32W91A18\",\n" +
//                            "                    \"MESSAGENAME\": \"PDALotInoResponse\",\n" +
//                            "                    \"EVENTUSER\": \"EAP\",\n" +
//                            "                    \"EVENTTIME\": \"2021-03-25 16:28:59.585\"\n" +
//                            "          },\n" +
//                            "          \"BODY\":           {\n" +
//                            "                    \"WORK_NO\": \"007\",\n" +
//                            "                    \"EQPID\": \"WB001\",\n" +
//                            "                    \"LOTID\":\"lotid\",\n" +
//                            "                    \"FILENO\": \"fileno\",\n" +
//                            "                    \"PRODUCTMODEL\": \"productmodel\",\n" +
//                            "                    \"INPUTQTY\": \"555\",\n" +
//                            "                    \"CURRENTPROCESS\": \"aaa\",\n" +
//                            "                    \"PROCESS\": \"zzz\",\n" +
//                            "                    \"MATERIALLISTs\":[\n" +
//                            "                               {\"MATERIAL_ID\":\"111\",\"MAT_NO\":\"111\",\"MATERIAL_NAME\":\"111\",\"SPECS\":\"111\",\"MATERIAL_TYPE\":\"111\"},\n" +
//                            "                               {\"MATERIAL_ID\":\"222\",\"MAT_NO\":\"222\",\"MATERIAL_NAME\":\"222\",\"SPECS\":\"222\",\"MATERIAL_TYPE\":\"222\"},\n" +
//                            "{\"MATERIAL_ID\":\"333\",\"MAT_NO\":\"333\",\"MATERIAL_NAME\":\"333\",\"SPECS\":\"333\",\"MATERIAL_TYPE\":\"333\"}\n" +
//                            "                     ]\n" +
//                            "\n" +
//                            "          },\n" +
//                            "          \"RETURN\":           {\n" +
//                            "                    \"RETURNCODE\": \"0\",\n" +
//                            "                    \"RETURNMESSAGE\": \"信息获取成功\"\n" +
//                            "          }\n" +
//                            "}";
//                    try {
//                        JSONObject jsonObject = new JSONObject(sJson);
//                        String body = jsonObject.getString("BODY");
//                        mPDALotInfoReturnEntity = GsonUtils.getObject(body, PDALotInfoReturnEntity.class);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
                    //endregion
                    binding. setLotInfoEntity(mPDALotInfoReturnEntity);
                    if (mMaterialInfoList != null) {
                        mMaterialInfoList.clear();
                    }
//                    mMaterialInfoList.addAll(mPDALotInfoReturnEntity.getMATERIALLIST());
                    mMaterialInfoList.addAll(mPDALotInfoReturnEntity.getMATERIALLISTs());
                    materialAdapter.setNewData(mMaterialInfoList);
                }
            }

            @Override
            public void onError(Response<ResponseEntity<PDALotInfoReturnEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDALotInfo");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("WORK_NO", Constant.loginEntity.getWORK_NO());
        map.addProperty("EQPID", sEqpId);
        map.addProperty("LotID", sLotId);
        String method = "PDALotInfo";
        NetUtils.requestPostNet("PDALotInfoRequest", method, this, map, callBack);
    }

    //开始作业
    private void startProcess() {
        FreeUI_EntityCallBack<ResponseEntity<?>> callBack = new FreeUI_DialogEntityCallBack<ResponseEntity<?>>(new TypeToken<ResponseEntity<?>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseEntity<?>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(false, getSupportFragmentManager())) {
                    showMessageDialog(response.body().getMsg(), getSupportFragmentManager());
//                    finish();
                }
            }

            @Override
            public void onError(Response<ResponseEntity<?>> response) {
                super.onError(response);
                loadError(response.getException(), "PDATrackIn");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("WORK_NO", Constant.loginEntity.getWORK_NO());//工号
        map.addProperty("EQUIPMENTID", mPDALotInfoReturnEntity.getEQPID());//设备号
        map.addProperty("LotID", mPDALotInfoReturnEntity.getLOTID());//批次
        map.addProperty("CURRENTPROCESS", mPDALotInfoReturnEntity.getCURRENTPROCESS());//当前站点
        map.addProperty("FILENO", mPDALotInfoReturnEntity.getFILENO());//文件序号
        map.addProperty("PRODUCTMODEL", mPDALotInfoReturnEntity.getPROCESS());//产品型号
        map.addProperty("INPUTQTY", mPDALotInfoReturnEntity.getINPUTQTY());//数量
        map.addProperty("PROCESS", mPDALotInfoReturnEntity.getPROCESS());//工序

        String method ="PDATrackIn";
        NetUtils.requestPostNet("PDATrackInRequest", method, this, map, callBack);
    }

    //endregion

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_query) {
            Bundle bundle = new Bundle();
            bundle.putString("EQPID", sEqpId);
            bundle.putString("Process", mPDALotInfoReturnEntity.getPROCESS());
            FreeApi_Utils.skipWithExtraIntent("header", bundle, mContext, MaterialExchangeActivity.class);

        } else if (v.getId() == R.id.llMaterialLayout) {

            if (binding.llMaterial.getVisibility() == View.GONE) {
                binding.llMaterial.setVisibility(View.VISIBLE);
                binding.ivShow.setImageDrawable(getResources().getDrawable(R.drawable.down_arrow));
            } else {
                binding.llMaterial.setVisibility(View.GONE);
                binding.ivShow.setImageDrawable(getResources().getDrawable(R.drawable.room_right_arrow));
            }
        }
    }

    //消息提示框
    protected void showMessageDialog(String message, FragmentManager fragmentManager) {
        FreeApi_DialogUtils.getConfirmDialog(
                App.app, "确定", message, this::finish
        ).show(fragmentManager, "DIALOG");
    }

}